﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Data.Linq;
using System.Configuration;
using Common.Background.Entity;

namespace Common.Background.Data
{

    /// <summary>
    /// 数据库建立工厂
    /// Created By : 张占岭
    /// Created Date：2011-10-14
    /// Modify By:
    /// Modify Date:
    /// Modify Reason:
    /// </summary>
    internal static class DbFactory
    {
        static string strConn = ConfigurationManager.ConnectionStrings["Background"].ToString();
        static System.Timers.Timer sysTimer = new System.Timers.Timer(10000);
        volatile static Dictionary<Thread, DataContext[]> divDataContext = new Dictionary<Thread, DataContext[]>();
        static DbFactory()
        {
            sysTimer.AutoReset = true;
            sysTimer.Enabled = true;
            sysTimer.Elapsed += new System.Timers.ElapsedEventHandler(sysTimer_Elapsed);
            sysTimer.Start();
        }

        static void sysTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            List<Thread> list = divDataContext.Keys.Where(item => item.ThreadState == ThreadState.Stopped).ToList();
            for (int index = 0; index < list.Count; index++)
            {
                for (int refer = 0; refer < divDataContext[list[index]].Length; refer++)
                    if (divDataContext[list[index]][refer] != null)
                    {
                        divDataContext[list[index]][refer].Dispose();
                        divDataContext[list[index]][refer] = null;
                    }
                divDataContext.Remove(list[index]);
                list[index] = null;
            }
        }

        /// <summary>
        /// 通过工厂的制造模式获取相应的LINQ数据库连接对象
        /// </summary>
        /// <param name="dbName">数据库名称(需要与真实数据库名称保持一致)</param>
        /// <returns>LINQ数据库连接对象</returns>
        public static DataContext Intance(string dbName)
        {
            return Intance(dbName, Thread.CurrentThread);
        }

        /// <summary>
        /// 通过工厂的制造模式获取相应的LINQ数据库连接对象
        /// </summary>
        /// <param name="dbName">数据库名称(需要与真实数据库名称保持一致)</param>
        /// <param name="thread">当前线程引用的对象</param>
        /// <returns>LINQ数据库连接对象</returns>
        public static DataContext Intance(string dbName, Thread thread)
        {

            if (!divDataContext.Keys.Contains(thread))
            {
                divDataContext.Add(thread, new DataContext[1]);
            }

            if (dbName.Equals("Background"))
            {
                if (divDataContext[thread][0] == null)
                {
                    divDataContext[thread][0] = new LinqBackgroundDataContext(strConn);
                }
                return divDataContext[thread][0];
            }
            return null;
        }
    }
}
